﻿using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Net;

class TcpClientDemo
{
    const int RECEIVE_BUF_SIZE = 4096;

    static void Main()
    {
        TcpClient tcpClient = new TcpClient();
        try
        {
            tcpClient.Connect("localhost", 80);
        }
        catch (SocketException)
        {
            Console.WriteLine("Error: Unable to connect to the server.");
            return;
        }

        using (tcpClient)
        {
            NetworkStream netStream = tcpClient.GetStream();
            using (netStream)
            {

                // Send HTTP GET request to the Web server
                try
                {
                    StreamWriter writer = new StreamWriter(netStream);
                    writer.WriteLine("GET http://localhost/ HTTP/1.0");
                    writer.WriteLine();
                    writer.Flush();
                }
                catch (IOException)
                {
                    Console.WriteLine("Error: Can not send request.");
                    return;
                }

                // Receive the HTTP answer from the server
                try
                {
                    byte[] buf = new byte[RECEIVE_BUF_SIZE];
                    while (true)
                    {
                        int bytesRead = netStream.Read(buf, 0, buf.Length);
                        if (bytesRead == 0)
                        {
                            // Server closed the connection
                            break;
                        }
                        string data = Encoding.ASCII.GetString(buf, 0, bytesRead);
                        Console.Write(data);
                    }
                }
                catch (IOException)
                {
                    Console.WriteLine("Error: Can not read the server response.");
                }
            }
        }
    }
}